package com.tpc.yaoxpt.main;

import com.tpc.yaoxpt.job.*;
import com.tpc.yaoxpt.utils.AlertUtil;
import com.tpc.yaoxpt.utils.FileUtil;
import com.tpc.yaoxpt.utils.JDBCUtil;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.util.Arrays;
import java.util.Map;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    final PTModule ptModule = new PTModule();

    final DBModule dbModule = new DBModule();

    final ConfigModule configModule = new ConfigModule();

    final LogModule logModule = LogModule.getInstance();

    final GoodsJob goodsJob = new GoodsJob();

    final BusinessJob businessJob = new BusinessJob();

    final PurOrderJob purOrderJob = new PurOrderJob();

    final DisOrderJob disOrderJob = new DisOrderJob();

    final DisOrderRepairJob disOrderRepairJob = new DisOrderRepairJob();

    @FXML
    private TextArea logText;

    public static TextArea staticLogText;

    @FXML
    private TextField entNameText;

    @FXML
    private TextField urlText;

    @FXML
    private TextField apiKeyText;

    @FXML
    private TextField dbIpText;

    @FXML
    private TextField dbPasswordText;

    @FXML
    private TextField dbNameText;

    @FXML
    private TextField dbPortText;

    @FXML
    private ComboBox<String> dbTypeText;

    @FXML
    private TextField dbUserText;

    @FXML
    private TextField secretKeyText;

    @FXML
    private TextField logCountText;

//    public MainController(String info) {
//        logText.appendText("\n" + info);
//    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        staticLogText = logText;

        //给ComboBox 设置初始值
        ObservableList<String> dbTypeList = FXCollections.observableArrayList("MSSQL", "ORACLE","MYSQL");
        dbTypeText.setItems(dbTypeList);


        int maxLines = 0;
        try {
            maxLines = Integer.parseInt(FileUtil.getConfigConfig().get("LOGCOUNT")) == 0 ? 300 : Integer.parseInt(FileUtil.getConfigConfig().get("LOGCOUNT"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        int finalMaxLines = maxLines;
        logText.textProperty().addListener((observable, oldValue, newValue)->{
            String[] lines = logText.getText().split("\n");
            if (lines.length > finalMaxLines) {
                lines = Arrays.copyOfRange(lines,
                        lines.length - finalMaxLines, lines.length);
                String text = String.join("\n", lines);
                logText.setText(text);
            }
        });

        // 设置监听
//        logModule.logInfoProperty().addListener(new InvalidationListener() {
//            @Override
//            public void invalidated(Observable observable) {
//                logText.setText(logModule.getLogInfo());
//                logText.setScrollTop(Double.MAX_VALUE);
//                logText.setScrollLeft(0);
//            }
//        });

        ptModule.entNameProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                entNameText.setText(ptModule.getEntName());
            }
        });

        ptModule.urlProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                urlText.setText(ptModule.getUrl());
            }
        });

        ptModule.apiKeyProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                apiKeyText.setText(ptModule.getApiKey());
            }
        });

        ptModule.secretKeyProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                secretKeyText.setText(ptModule.getSecretKey());
            }
        });

        dbModule.dbTypeProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbTypeText.setValue(dbModule.getDbType());
            }
        });

        dbModule.dbIpProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbIpText.setText(dbModule.getDbIp());
            }
        });

        dbModule.dbUserProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbUserText.setText(dbModule.getDbUser());
            }
        });

        dbModule.dbPasswordProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbPasswordText.setText(dbModule.getDbPassword());
            }
        });

        dbModule.dbNameProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbNameText.setText(dbModule.getDbName());
            }
        });

        dbModule.dbPortProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                dbPortText.setText(dbModule.getDbPort());
            }
        });

        configModule.logCountProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                logCountText.setText(configModule.getLogCount());
            }
        });

        try {
            Map<String, String> dbConfig = FileUtil.getDBConfig();
            dbModule.setDbType(dbConfig.get("DBTYPE"));
            dbModule.setDbIp(dbConfig.get("DBIP"));
            dbModule.setDbUser(dbConfig.get("DBUSER"));
            dbModule.setDbPassword(dbConfig.get("DBPASSWORD"));
            dbModule.setDbName(dbConfig.get("DBNAME"));
            dbModule.setDbPort(dbConfig.get("DBPORT"));
        } catch (IOException e) {
            AlertUtil.FAIL("数据库配置信息获取失败！", e.getMessage());
            throw new RuntimeException(e);
        }

        try {
            Map<String, String> ptConfig = FileUtil.getPTConfig();
            ptModule.setEntName(ptConfig.get("ENTNAME"));
            ptModule.setUrl(ptConfig.get("URL"));
            ptModule.setApiKey(ptConfig.get("APIKEY"));
            ptModule.setSecretKey(ptConfig.get("SECRETKEY"));
        } catch (IOException e) {
            AlertUtil.FAIL("平台配置信息获取失败！", e.getMessage());
            throw new RuntimeException(e);
        }

        try {
            Map<String, String> configConfig = FileUtil.getConfigConfig();
            configModule.setLogCount(configConfig.get("LOGCOUNT"));
        } catch (IOException e) {
            AlertUtil.FAIL("设置中心信息获取失败！", e.getMessage());
            throw new RuntimeException(e);
        }

    }
    @FXML
    protected void onGetGoodsInfoClick(){
//        GoodsService goodsService = new GoodsService();
//        goodsService.getGoodsInfo();
        //        GoodsJob goodsJob = new GoodsJob();
//        logModule.appendLogInfo("\n 获取商品任务开始");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取商品任务开始");
            }
        });
        goodsJob.execScheduledService();
    }

    @FXML
    protected void onGetGoodsInfoStopClick(){
//        GoodsScheduleService goodsScheduleService = new GoodsScheduleService();
//        goodsScheduleService.cancel();
//        logModule.appendLogInfo("\n 获取商品任务暂停");
//        GoodsJob goodsJob = new GoodsJob();
        goodsJob.stopScheduledService();
//        logModule.appendLogInfo("\n 获取商品任务结束");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取商品任务结束");
            }
        });
    }

    @FXML
    protected void onGetBusinessInfoClick(){
//        BusinessService businessService = new BusinessService();
//        businessService.getBusinessInfo();
//        logModule.appendLogInfo("\n 获取医疗机构任务开始");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取医疗机构任务开始");
            }
        });
        businessJob.execScheduledService();
    }

    @FXML
    protected void onGetBusinessInfoStopClick(){
        businessJob.stopScheduledService();
//        logModule.appendLogInfo("\n 获取医疗机构任务结束");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取医疗机构任务结束");
            }
        });
    }


    @FXML
    protected void onGetPurOrderInfoClick(){
//        PurOrderService purOrderService = new PurOrderService();
//        purOrderService.getPurOrderInfo();
//        logModule.appendLogInfo("\n 获取采购订单任务开始");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取采购订单任务开始");
            }
        });
        purOrderJob.execScheduledService();
    }
    @FXML
    protected void onGetPurOrderInfoStopClick(){
//        PurOrderService purOrderService = new PurOrderService();
//        purOrderService.getPurOrderInfo();
        purOrderJob.stopScheduledService();
//        logModule.appendLogInfo("\n 获取采购订单任务结束");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 获取采购订单任务结束");
            }
        });
    }

    @FXML
    protected void onUploadClick(){
//        logModule.appendLogInfo("\n 上传任务开始");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 上传任务开始");
            }
        });
        disOrderJob.execScheduledService();
        disOrderRepairJob.execScheduledService();
    }

    @FXML
    protected void onUploadStopClick(){
        disOrderJob.stopScheduledService();
        disOrderRepairJob.stopScheduledService();
//        logModule.appendLogInfo("\n 上传任务结束");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.appendText("\n 上传任务结束");
            }
        });
    }

    @FXML
    protected void onAllStartClick(){
        onGetGoodsInfoClick();
        onGetBusinessInfoClick();
        onGetPurOrderInfoClick();
        onUploadClick();
    }

    @FXML
    protected void onAllStopClick(){
        onGetGoodsInfoStopClick();
        onGetBusinessInfoStopClick();
        onGetPurOrderInfoStopClick();
        onUploadStopClick();
    }

    @FXML
    protected void onDBTestSaveClick(){
        Connection connection = null ;
        try {
            connection = JDBCUtil.getConnection();
            AlertUtil.alert("数据库连接成功！");
        } catch (Exception e) {
            AlertUtil.FAIL("数据库链接失败！",e.getMessage());
        }finally {
            JDBCUtil.close(connection);
        }
    }

    @FXML
    protected void onClearLogClick(){
//        logModule.setLogInfo("");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                MainController.staticLogText.setText("");
            }
        });
    }

    @FXML
    protected void onPTSaveClick() {
        try {
            FileUtil.addSection("PTCONFIG","ENTNAME",entNameText.getText());
            FileUtil.addSection("PTCONFIG","URL",urlText.getText());
            FileUtil.addSection("PTCONFIG","APIKEY",apiKeyText.getText());
            FileUtil.addSection("PTCONFIG","SECRETKEY",secretKeyText.getText());
        } catch (IOException e) {

            throw new RuntimeException(e);
        }
        AlertUtil.SAVESUCCESS();
    }

    @FXML
    protected void onDBSaveClick() {
        try {
            FileUtil.addSection("DBCONFIG","DBTYPE",dbTypeText.getValue());
            FileUtil.addSection("DBCONFIG","DBIP",dbIpText.getText());
            FileUtil.addSection("DBCONFIG","DBUSER",dbUserText.getText());
            FileUtil.addSection("DBCONFIG","DBPASSWORD",dbPasswordText.getText());
            FileUtil.addSection("DBCONFIG","DBNAME",dbNameText.getText());
            FileUtil.addSection("DBCONFIG","DBPORT",dbPortText.getText());
        } catch (IOException e) {
            AlertUtil.FAIL("保存失败！",e.getMessage());
            throw new RuntimeException(e);
        }
        AlertUtil.SAVESUCCESS();
    }
    @FXML
    protected void onConfigSaveClick(){
        try {
            FileUtil.addSection("CONFIG","LOGCOUNT",logCountText.getText());
        } catch (IOException e) {
            AlertUtil.FAIL("保存失败！",e.getMessage());
            throw new RuntimeException(e);
        }
        AlertUtil.SAVESUCCESS();
    }


}